package com.xt.shop.Controller;

import com.xt.shop.Model.GoodsInfo;
import com.xt.shop.Model.RestBean;
import com.xt.shop.service.impl.GoodsInfoServiceImpl;
import com.xt.shop.service.impl.ShopInfoServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/api/goods")
public class GoodsController {

    @Resource
    GoodsInfoServiceImpl service;

    @Resource
    ShopInfoServiceImpl shopInfoService;

    @RequestMapping("/select/{page}/{item}")
    public RestBean selectByPage(@PathVariable int page,@PathVariable int item,String name){
        return RestBean.success(service.queryGoods(page,item,name));
    }

    @RequestMapping("/get/{id}")
    public RestBean getOne(@PathVariable String id){
        GoodsInfo byId = service.getById(id);
        return byId == null ?RestBean.failure(400,"参数异常"):RestBean.success(byId);
    }

    @RequestMapping("/del/{id}")
    public RestBean del(@PathVariable int id){
        GoodsInfo byId = service.getById(id);
        if (byId != null){
            byId.setState(-1);
            if (service.updateById(byId)){
                return RestBean.success(byId);
            }
            return RestBean.failure(500,"删除失败");
        }
        return RestBean.failure(400,"参数异常");
    }

    @RequestMapping("/insert")
    public RestBean insert(@RequestBody GoodsInfo goodsInfo){
        String uuid = UUID.randomUUID().toString();
        goodsInfo.setGoodsId(uuid);
        goodsInfo.setState(1);
        goodsInfo.setInputTime(new Date());
        goodsInfo.setUpdateTime(new Date());
        if (service.save(goodsInfo)){
            return RestBean.success(service.getById(uuid) );
        }
        return RestBean.failure(500,"新建失败");
    }


    @RequestMapping("/update")
    public RestBean update(@RequestBody GoodsInfo goodsInfo) {
        GoodsInfo byId = service.getById(goodsInfo.getGoodsId());
        if (byId != null) {
            goodsInfo.setUpdateTime(new Date());
            goodsInfo.setInputTime(byId.getInputTime());
            if (service.updateById(goodsInfo)) {
                return RestBean.success(goodsInfo);
            }
            return RestBean.failure(500, "更新失败");
        }
        return RestBean.failure(400,"参数异常");
    }

}
